package com.raymond.close;

import com.raymond.netty.NettyStart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * 程序关闭运行
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2020-05-25 17:44
 */
@Slf4j
@Component
public class EndGlobalKeyboard implements ApplicationListener<ContextClosedEvent> {

    private final ThreadPoolTaskExecutor threadExecutor;

    private final NettyStart nettyStart;

    public EndGlobalKeyboard(ThreadPoolTaskExecutor threadExecutor, NettyStart nettyStart) {
        this.threadExecutor = threadExecutor;
        this.nettyStart = nettyStart;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {

        threadExecutor.shutdown();
        //优雅退出，释放线程池资源
        nettyStart.parent.shutdownGracefully();
        nettyStart.child.shutdownGracefully();
        log.info("程序正在退出......");
        while (threadExecutor.getActiveCount() != 0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("线程休眠异常", e);
            }
        }
        log.info("程序正常退出");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("线程休眠异常", e);
        }
    }
}
